package com.zhu.utils;


import java.sql.*;


public class JDBCUtil {
    /**
     * 获取连接方法
     * @return
     */
    private volatile static JDBCUtil jdbcUtil;
    private  Connection conn = null;
    private static String url;
    private static String username;
    private static String password;
    private static String driver;
    static{

//从文件中读取内容---使用load方法加载
        try {

            driver = "com.mysql.jdbc.Driver";
            url = "jdbc:mysql://120.79.115.206:3306/javaweb";
            username = "javaweb";
            password = "123456";
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            System.err.println(e);
        }

    }
    private JDBCUtil() {
    }

    public static JDBCUtil getInstance() {
        if (jdbcUtil == null) {
            synchronized (JDBCUtil.class) {
                if (jdbcUtil == null) {
                    jdbcUtil = new JDBCUtil();
                }
            }
        }
        return jdbcUtil;
    }


    public Connection getConnection(){
      if(conn==null){
          try {
              conn = DriverManager.getConnection(url,username,password);
          } catch (SQLException throwables) {
              System.err.println(throwables);
          }
      }
        return conn;
    }

    /**
     * 释放资源方法
     * @param conn
     * @param pstmt
     * @param rs
     */

    public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                System.err.println(e);
            }
        }

        if(pstmt != null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                System.err.println(e);
            }
        }

        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                System.err.println(e);
            }
        }

    }
}
